package me.ezitku.base.extensions

import android.view.View
import android.widget.AdapterView
import android.widget.Spinner
import java.util.ArrayList

/**
 * Created by yurqi on 2017/5/18.
 */


fun Spinner.selectedListener(action: OnItemSelectedeListener.() -> Unit) {
    onItemSelectedListener = OnItemSelectedeListener().apply(action)
}

fun Spinner.toAdapter() {

}

class OnItemSelectedeListener : AdapterView.OnItemSelectedListener {
    var _onSelected: ((position: Int) -> Unit)? = null
    override fun onNothingSelected(parent: AdapterView<*>?) {

    }

    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        _onSelected?.invoke(position)
    }

    fun onSelected(listener: (position: Int) -> Unit) {
        _onSelected = listener
    }

}


/**
 * @param data
 * @param action
 *  شەرتكە ئاساسەن spinner نى ئاپتۇماتىك تاللايدۇ
 */
fun <T> Spinner.selection(data: ArrayList<T>, action: (position: Int) -> Boolean) {
    for (i in data.indices) {
        if (action.invoke(i)) {
            this.setSelection(i)
            break
        }
    }
}

/**
 * @param data
 * @param action
 *  شەرتكە ئاساسەن spinner نى ئاپتۇماتىك تاللايدۇ
 */
fun <T> Spinner.autoSelect(data: ArrayList<T>, action: (position: Int) -> Boolean) {
    for (i in data.indices) {
        if (action.invoke(i)) {
            this.setSelection(i)
            break
        }
    }
}
